const jwt = require("jsonwebtoken");
const assert = require("http-assert");

const AdminUser = require("../models/AdminUser");

module.exports = (options) => {
  return async (req, res, next) => {
    const token = String(req.headers.authorization || "")
      .split(" ")
      .pop();
    assert(token, 401, "请先登录");
    try {
      const { _id } = jwt.verify(token, req.app.get("secret"));
      assert(_id, 401, "请先登录");
      req.user = await AdminUser.findById(_id);
      assert(req.user, 401, "请先登录");
    } catch (e) {
      e.statusCode = 401;
      e.message = "登录超时,请重新登录";
      throw e;
    }
    await next();
  };
};
